/*
 * @lc app=leetcode.cn id=606 lang=cpp
 *
 * [606] 根据二叉树创建字符串
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
  string tree2str(TreeNode* root)
  {
    string ans = DFS(root);
    ans.pop_back();
    ans.erase(ans.begin());
    return ans;
  }

  string DFS(TreeNode* root)
  {
    // 非叶节点
    if (root->left || root->right) {
      string tmp = "(" + to_string(root->val);
      if (root->left)
        tmp += DFS(root->left);
      else
        tmp += "()";
      if (root->right)
        tmp += DFS(root->right);
      tmp.push_back(')');
      return tmp;
    }
    // 叶节点
    else
      return "(" + to_string(root->val) + ")";
  }
};
// @lc code=end
